package com.album.activity.base;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.album.R;
import com.album.activity.SetstateManager;
import com.album.activity.MessageDialog;
import com.album.activity.page.PageManager;
import com.album.activity.pageView.MyFriendsView;
import com.album.activity.pageView.MyPhotoView;
import com.album.activity.pageView.UserLoginView;
import com.album.bean.ErrorInfo;
import com.album.bean.UserInfo;
import com.album.bean.loginInfo;
import com.album.common.Constants;
import com.album.provider.ProviderUtil;
import com.album.task.GetUserInfoTask;
import com.album.task.ICallBack;
import com.album.task.Task;
import com.album.task.UserLoginTask;
import com.album.utils.CommonUtil;
import com.album.utils.JsonUtils;
import com.album.utils.MyLog;
import com.google.gson.Gson;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class BaseView {
	private Context context;
	private View view;		//总视图 
	protected Toast toast;
	private ProgressDialog dialog_login; 
	private ProgressDialog dialog_userInfo; 
	protected SharedPreferences ferences = null;
	private static final int LOGIN = 99;
	private static final int LOGIN_SUC = 100;
	private static final int LOGIN_FAIL = 101;
	private final int USER_INFO_SUC=111;
	private final int USER_INFO_FAIL=112;
	private final int TIME_OUT=113;
	private CheckBox checkBox;
	private boolean login_status = false;
	private OperateHandler handler;
	private Class c;
	private PageManager manager;
	public BaseView(Class c,Context context,int layoutId,PageManager manager){
		this.context = context; 
		this.c=c;
		this.manager = manager;
		this.view = LayoutInflater.from(context).inflate(layoutId, null);
		handler = new OperateHandler();
		setMain();
	} 
	
	public void setMain(){ 
		final EditText userEidtText = (EditText)view.findViewById(R.id.username);
		final EditText pwdEidtText = (EditText)view.findViewById(R.id.password);
		Button btnLogin = (Button)view.findViewById(R.id.btn_login);
		Button btnRegister = (Button)view.findViewById(R.id.btn_register);
		Log.i("", "----------------------------------------:"+btnLogin);
		checkBox = (CheckBox)view.findViewById(R.id.check_login);
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//login thread...
//				if(!flgs){
					String userName= getEditTextValue(userEidtText);
					String pwd= getEditTextValue(pwdEidtText);
					
					Log.i("", "--------------------kicok--------------------:"+ v);
					if("" !=userName && ""!=pwd ){
						MyLog.debug(c, "userName:"+userName+ " pwd:"+pwd);
						loginThread(userName, pwd);
//						dialog = ProgressDialog.show(context, "", context.getText(R.string.bussiness_doing), true);
//						new loginTask().execute(userName,pwd);
					}
					else{
						MessageDialog.showToast(context, false, getRestring(R.string.label_login_error));
					}
//				}
			}
		});
		
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//register...
				String regisURL ="http://wap.189.cn/webmail/jsp/wapmail/register.jsp";
				Uri uri = Uri.parse(regisURL);
			    Intent i = new Intent(Intent.ACTION_VIEW, uri);
			    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			    context.startActivity(i);
			}
		});
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton paramCompoundButton, boolean isCheck) {
				// TODO Auto-generated method stub
				login_status = isCheck;
				MyLog.debug(context.getClass(), "login_status:"+login_status);
			}
		});
	}
		
	private String loginName,loginPwd;
	
	private void loginThread(String userName,String pwd){
		dialog_login = ProgressDialog.show(context, "", context.getText(R.string.login_doing), true);
//		userName="18926128667@189.cn";
		/**
		 * 帐号：18926128667
			密码：128667
			
			青风(16090328)  22:25:45
			帐号：18926128626
			密码：2001123456

		 */
//		userName="18926128667@189.cn";
//		pwd = "128667";
		
		userName="18926128626@189.cn";
		pwd = "2001123456";
		
		loginName = userName;
		loginPwd = pwd;
		//pwd = "";
		//调接口进行登录操作
		String imsi="460036241155921";
		//String imsi = CommonUtil.getIMSI(context);
		final Gson gson = new Gson();
		Task loginTask = new UserLoginTask(context,imsi,userName,pwd,new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
			}
			@Override
			public void CallBack(String rspString) {
				MyLog.info(getClass(), "login resp:"+rspString);
				loginInfo info = gson.fromJson(rspString.toString(), loginInfo.class);
				if(info.getMsg()){
					Message ms = new Message();
					ms.obj = info;
					ms.what = LOGIN;
					handler.sendMessage(ms);
				}else{
					Message ms = new Message();
					ms.obj = info;
					ms.what = LOGIN_FAIL;
					handler.sendMessage(ms);
				}
			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
		});
		loginTask.doTask(loginTask);
		//登录
	}
	/**
	 * 获取用户信息
	 */
	private void getUserInfo(){
		//dialog_userInfo = ProgressDialog.show(context, "", context.getText(R.string.userinfo_doing), true);
		//String username="18926128667@189.cn";
		String username=CommonUtil.getUserName(context);
		Task task = new GetUserInfoTask(context,username, new ICallBack() {
			@Override
			public void CallBack(String imageUrl, Bitmap bm) {
				// TODO Auto-generated method stub
			}
			@Override
			public void CallBack(String rspString) {
				if (validateMessage(rspString)) {
					try {
						rspString = "[" + rspString + "]";
						JSONArray array = new JSONArray(rspString);
						JSONObject obj = array.getJSONObject(0);
						if (obj.getBoolean("msg")) {
							UserInfo info = new UserInfo();
							JSONObject res = obj.getJSONObject("data");
							MyLog.info(getClass(), "jsonData:" + res.toString());
							info = (UserInfo) JsonUtils.parseJson2Obj(
									res.toString(), UserInfo.class);
							ProviderUtil.insertOrUpdateUserInfo(context, info);
							Message ms = new Message();
							ms.obj = info;
							ms.what = USER_INFO_SUC;
							handler.sendMessage(ms);
						} else {
							UserInfo info = new UserInfo();
							info.setErrCode(obj.getString("errCode"));
							Message ms = new Message();
							ms.obj = info;
							ms.what = USER_INFO_FAIL;
							handler.sendMessage(ms);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			}
			@Override
			public void TimeOut() {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
			@Override
			public void HttpError(int errorCode) {
				// TODO Auto-generated method stub
				handler.sendEmptyMessage(TIME_OUT);
			}
		});
		task.doTask(task);
	}
	  class OperateHandler extends Handler {
			@Override
			public void handleMessage(Message msg) {
				// 更新界面
			switch (msg.what) {
			case LOGIN:
				loginInfo info = (loginInfo) msg.obj;
				MyLog.debug(getClass(), info.getErrCode());
				MyLog.debug(getClass(), info.getMsg() + "");
//				setLoginStatus(true);
				MessageDialog.showToast(context, true, getRestring(R.string.label_login_succend));
				if (dialog_login != null && dialog_login.isShowing())
					dialog_login.dismiss();
					handler.sendEmptyMessage(LOGIN_SUC);
				break;
			case LOGIN_FAIL:
				loginInfo info_fail = (loginInfo) msg.obj;
				MessageDialog.showToast(context, false,
						ErrorInfo.errorMap.get(info_fail.getErrCode()));
				if (dialog_login != null && dialog_login.isShowing())
					dialog_login.dismiss();
				break;
			case LOGIN_SUC: // 登录成功
				MyLog.debug(getClass(), "登录成功:"+c);
				//if(login_status){	//checkBox选中
					CommonUtil.setUserInfo(loginName, loginPwd, context);
				//}
				if(c == SetstateManager.MyPhotoView){
					MyLog.debug(getClass(), "跳转成功");
					 try {
						manager.activePage(MyPhotoView.class, null);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if(c == SetstateManager.MyFriendsView){
					 try {
							manager.activePage(MyFriendsView.class, null);
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
				else if(c == SetstateManager.MainActivity){
					//跳转
				}
				//获取用户资料
				getUserInfo();
			case USER_INFO_SUC:
				if (dialog_userInfo != null && dialog_userInfo.isShowing())
					dialog_userInfo.dismiss();
				break;
			case USER_INFO_FAIL:
				UserInfo userinfo_fail = (UserInfo) msg.obj;
				MessageDialog.showToast(context, false,
						ErrorInfo.errorMap.get(userinfo_fail.getErrCode()));
				if (dialog_userInfo != null && dialog_userInfo.isShowing())
					dialog_userInfo.dismiss();
				break;
			case TIME_OUT:
				if (dialog_login != null && dialog_login.isShowing())
					dialog_login.dismiss();
				if (dialog_userInfo != null && dialog_userInfo.isShowing())
					dialog_userInfo.dismiss();
				MessageDialog.showToast(context, false, context.getString(R.string.int_timeout));
				break ;
				}
			}
	}
	  
	/**
	 * 返回结果有效性验证
	 * @param jsonData
	 * @return
	 */
	public boolean validateMessage(String jsonData) {
		// 数据不存在
		if (null == jsonData || "".equals(jsonData)){
			return false;
		}
		return true;
	}
	
	public Handler baseHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				
				break;

			default:
				break;
			}
		}
	};
	
	//保存用户信息
	private void setUserInfo(String userName,String pwd){
		if(ferences==null)
			ferences = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edit = ferences.edit();
		edit.putString(Constants.SESSION_USER_NAME, userName);
		edit.putString(Constants.SESSION_USER_PASS, pwd);
		edit.commit();
	}
	
		
	public String getRestring(int resID){
		return context.getResources().getString(resID);
	}
	
		
	public final String getEditTextValue(EditText et) {
		if (et == null)
			return null;
		String tmp = "";
		if (et!=null) {
			if(et.getText().toString().trim().length()>0)
				tmp = et.getText().toString().trim();
		}
		return tmp;
	}
	public View getView(){
		return view;
	}
}
